﻿function json_decode( json ) {
	if ( json == "" )
		return;

	if ( typeof JSON !== "undefined" && typeof JSON.parse === "function" )
		return JSON.parse( json );
	else if ( json = eval( "(" + json + ")" ) )
		return json;

	return false;
};
$(function() {
	$("#submit").click(function() {
		$("#content").slideUp("slow", function() {
			$.ajax({
				url: "ajax.php",
				type: "POST",
				dataType: "html",
				data: "json=" + encodeURIComponent( $("#json").val() ) + "&default=" + encodeURIComponent( $("#default").val() ),
				success: function( response ) {
					if ( response == "BADREQUEST" ) {
						$("#content").slideDown();
						return;
					}

					$("#content").html("<p><label>@resource URL:</label><input type='text' id='resource' /></p>")
						.find("#resource")
						.val( response );
					$("#content").slideDown();
				},
				error: function() {
					$("#content").slideDown();
				}
			});
		});
		return false;
	});
	$("#json").change(function() {
		if ( this.value == "" )
			return;

		var json = json_decode( this.value );

		if ( typeof json === "object" ) {
			for ( var value in json ) {
				$("#default").val( value );
				break;
			}
		}
	});
})